package iot

import (
	"errors"
	"gorm.io/gorm"
	"iot-base/common/eventtype"
)

type (
	AlarmState eventtype.AlarmState

	AlarmMode struct {
		db *gorm.DB
	}
)

func NewAlarmMode(db *gorm.DB) *AlarmMode {
	return &AlarmMode{
		db,
	}
}

func (m *AlarmMode) FindListCount(stationId string, startTime string, endTime string) (int64, error) {
	var total int64
	dbSession := m.db.Model(&AlarmState{})
	if stationId != "" {
		dbSession.Where("station_id = ?", stationId)
	}
	if startTime != "" && endTime != "" {
		dbSession.Where("time_changed >= ?", startTime)
		dbSession.Where("time_changed <= ?", endTime)
	}
	dbSession.Where("is_alarm = true")
	err := dbSession.Count(&total).Error
	return total, err
}

func (m *AlarmMode) FindList(stationId string, page int, size int, startTime string, endTime string) ([]AlarmState, error) {
	var list []AlarmState
	dbSession := m.db.Model(&AlarmState{})
	if stationId != "" {
		dbSession.Where("station_id = ?", stationId)
	}

	if startTime != "" && endTime != "" {
		dbSession.Where("time_changed >= ?", startTime)
		dbSession.Where("time_changed <= ?", endTime)
	}

	dbSession.Where("is_alarm = true")
	dbSession.Limit(size).Offset((page - 1) * size)
	dbSession.Order("time_changed desc")
	dbSession.Find(&list)
	err := dbSession.Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return []AlarmState{}, nil
	}
	return append([]AlarmState{}, list...), err
}
func (m *AlarmMode) FindByStationByIdsCount(stationIds []string, startTime string, endTime string) (int64, error) {
	var total int64
	dbSession := m.db.Model(&AlarmState{})
	dbSession.Where("is_alarm = true")
	dbSession.Where("station_id in ?", stationIds)
	if startTime != "" && endTime != "" {
		dbSession.Where("time_changed >= ?", startTime)
		dbSession.Where("time_changed <= ?", endTime)
	}
	dbSession.Count(&total)
	err := dbSession.Error
	return total, err
}

func (m *AlarmMode) FindByStationByIdsList(stationIds []string, page, size int, startTime string, endTime string) ([]AlarmState, error) {
	var alarmList []AlarmState
	dbSession := m.db.Model(&AlarmState{})
	dbSession.Where("is_alarm = true")
	dbSession.Where("station_id in ?", stationIds)
	dbSession.Order("time_changed desc")

	if startTime != "" && endTime != "" {
		dbSession.Where("time_changed >= ?", startTime)
		dbSession.Where("time_changed <= ?", endTime)
	}

	dbSession.Limit(size).Offset((page - 1) * size)
	dbSession.Find(&alarmList)
	err := dbSession.Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return []AlarmState{}, nil
	}
	return append([]AlarmState{}, alarmList...), err
}

func (m *AlarmMode) FindByStationIdList(stationsId string) ([]AlarmState, error) {
	var alarmList []AlarmState
	dbSession := m.db.Model(&AlarmState{})
	dbSession.Where("is_alarm = true")
	dbSession.Where("station_id = ?", stationsId)
	dbSession.Find(&alarmList)
	err := dbSession.Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return []AlarmState{}, nil
	}
	return append([]AlarmState{}, alarmList...), err
}
